<?php

namespace control;
/*
*采购付款一览表类
*/

class purchasePayClass extends adIndexClass
{
    private const page = 'purchasePay';
    private const title = '采购付款一览表';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => '单据编号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'recordDate' => [
                        'name'  => "单据日期",
                        'width' => 130,
                        'sort' => 1,
                    ],
                    'settlementType'  => [
                        'name'  => "结算方式",
                        'width' => 100,
                    ],
                    'period'         => [
                        'name'  => '结算期限',
                        'width' => 130,
                    ],
                    'code'          => [
                        'name'  => '供应商编码',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'name'          => [
                        'name'  => '供应商',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'category'          => [
                        'name'  => '供应商类别',
                        'width' => 150,
                    ],
                    'payable'          => [
                        'name'  => '应付金额(' . static::$unit . ')',
                        'width' => 150,
                    ],
                    'recMoney'          => [
                        'name'  => '实际付款金额(' . static::$unit . ')',
                        'width' => 150,
                    ],
                    'residue'          => [
                        'name'  => '剩余应付金额(' . static::$unit . ')',
                        'width' => 150,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "供应商编码" => text(array("name" => "code")),
                    "供应商名称"   => text(array("name" => "name")),
                    "单据编号"   => text(array("name" => "orderNo")),
                ],
                [
                    '供应商类别'  => select(array("name" => "category", 'option' => para('supplierCategory', '，'), "title" => "供应商类别")),
                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            'b.code' => $this->post('code'),
            'b.name' => $this->post('name'),
            'a.orderNo' => $this->post('orderNo'),
        );
        //全等查询数组
        $equal = array(
            'b.category' => $this->post('category'),
            'a.coid' => self::$coid,
            'a.state' => '已确认'
        );
        $and = "";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'a.recordDate desc,a.orderNo',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => "purchase_get_order as a join supplier as b on a.supplierId = b.id",
            'field' => "a.*,b.name,b.code,b.category",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        $inReceipt = new inReceiptClass();
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            $liButton[] = $this->dominate($dominate);
            $saleMoney = find([
                'table' => 'record',
                'where' => "coid = '" . self::$coid . "' and orderNo = '$array[orderNo]' and classify not in ('核销', '付款单核销', '付款单')",
                'sum' => "money"
            ]);
            $saleMoney = abs($saleMoney);
            //退货退款
            $refundMoney = find([
                'table'=>'record',
                'field'=>"ifnull(sum(money),0) as total",
                'single'=>"coid = '".self::$coid."' and sourceId in (select id from inventory_detail where sourceId in (select id from purchase_refund_order_detail where sourceId in (select id from purchase_get_order_detail where orderId = '$array[id]')))"
            ])['total'];

            $saleMoney = round($saleMoney-$refundMoney,2);

            $recMoney = find([
                'table' => 'record',
                'where' => "coid = '" . self::$coid . "' and (sourceId in (select id from write_off_order_detail where sourceId = '$array[id]') or sourceId in (select id from receipt_source where sourceId = '$array[id]')) and classify in ('核销', '付款单核销', '付款单')",
                'sum' => "money"]);
            //调整金额
            $adjustMoney = find([
                'table' => 'purchase_esti_order_detail as a join purchase_get_order_detail as b on a.sourceId = b.id join purchase_order as main on b.orderId = main.id join inventory_detail as c on c.sourceId = a.id join record as d on c.id = d.sourceId',
                'single' => "a.coid = '" . self::$coid . "' and main.orderNo = '$array[orderNo]'",
                'field' => "ifnull(sum(d.money),0) as money"
            ])['money'];
            $adjustMoney = -$adjustMoney;
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "orderNo":
                        $row[] = componentClass::urlTitle($array['orderNo'], root . 'control/adIndex.html?cla=purchaseGetOrder&fun=detail&id=' . $array['id'], '采购收货单', 'hands-url');
                        break;
                    case "settlementType":
                        $settlementType = saleOrderClass::getPeriod($array['settlementType'], $array['settlementDay']);
                        $row[] = $settlementType;
                        break;
                    case "period":
                        $period = $inReceipt->settlementPeriod($array['settlementType'], $array['recordDate'], $array['settlementDay']);
                        $row[] = $period;
                        break;
                    case "payable":
                        $row[] = self::lostZero($saleMoney + $adjustMoney);
                        break;
                    case "recMoney":
                        $row[] = self::lostZero($recMoney);
                        break;
                    case "residue":
                        $row[] = self::formattingFigure($saleMoney + $adjustMoney - $recMoney);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        $saleMoney = find([
            "table" => "purchase_get_order as a join supplier as b on a.supplierId = b.id join record as c on a.orderNo = c.orderNo",
            'single' => $where . " and c.classify not in ('核销','付款单核销','付款单')",
            'field' => "ifnull(sum(c.money),0) as money"
        ])['money'];
        $saleMoney = abs($saleMoney);
        $refundMoney = find([
            "table" => "purchase_get_order as a join supplier as b on a.supplierId = b.id join record as c on (c.sourceId in (select id from inventory_detail where sourceId in (select id from purchase_refund_order_detail where sourceId in (select id from purchase_get_order_detail where orderId = a.id))))",
            'single'=>$where." and c.classify ='采购退货'",
            'field'=>"ifnull(sum(c.money),0) as money"
        ])['money'];
        $saleMoney = round($saleMoney-$refundMoney,2);
        $recMoney = find([
            "table" => "purchase_get_order as a join supplier as b on a.supplierId = b.id join record as c on (c.sourceId in (select id from write_off_order_detail where sourceId = a.id) or sourceId in (select id from receipt_source where sourceId = a.id))",
            'single' => $where . " and c.classify in ('核销','付款单核销','付款单')",
            'field' => "ifnull(sum(c.money),0) as money"
        ])['money'];
        //调整金额
        $adjustMoney = $this->loopMoney();
        /*$button .= self::titleSpan('应付金额合计', self::lostZero($saleMoney + $adjustMoney));
        $button .= self::titleSpan('实付金额合计', self::lostZero($recMoney));
        $button .= self::titleSpan('应付余额合计', self::lostZero(round($saleMoney + $adjustMoney - $recMoney, 2)));*/
        $total = [
            'payable' => self::lostZero($saleMoney + $adjustMoney),
            'recMoney' => self::lostZero($recMoney),
            'residue' => self::formattingFigure($saleMoney + $adjustMoney - $recMoney),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total" => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    public function loopMoney()
    {
        $all = self::sqlFind($_SESSION[self::page]['sql']);
        $money = 0;
        foreach ($all as $array) {
            //调整金额
            $adjustMoney = find([
                'table' => 'purchase_esti_order_detail as a join purchase_get_order_detail as b on a.sourceId = b.id join purchase_order as main on b.orderId = main.id join inventory_detail as c on c.sourceId = a.id join record as d on c.id = d.sourceId',
                'single' => "a.coid = '" . self::$coid . "' and main.orderNo = '$array[orderNo]'",
                'field' => "ifnull(sum(d.money),0) as money"
            ])['money'];
            $adjustMoney = -$adjustMoney;
            $money += $adjustMoney;
        }
        return round($money, 2);
    }

    public static function titleSpan($title, $value)
    {
        return <<<eof
<span class="span-title">{$title}：$value</span>
eof;

    }


    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }   else {
            $inReceipt = new inReceiptClass();
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => "purchase_get_order as a join supplier as b on a.supplierId = b.id",
                    'field' => "a.*,b.name,b.code,b.category",
                    "where" => "a.id in ('".implode("','", $checkedId)."') order by a.recordDate desc,a.orderNo desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $settlementType = saleOrderClass::getPeriod($array['settlementType'], $array['settlementDay']);
                $period = $inReceipt->settlementPeriod($array['settlementType'], $array['recordDate'], $array['settlementDay']);
                $saleMoney = find([
                    'table' => 'record',
                    'where' => "coid = '" . self::$coid . "' and orderNo = '$array[orderNo]' and classify not in ('核销', '付款单核销', '付款单')",
                    'sum' => "money"
                ]);
                $recMoney = find([
                    'table' => 'record',
                    'where' => "coid = '" . self::$coid . "' and (sourceId in (select id from write_off_order_detail where sourceId = '$array[id]') or sourceId in (select id from receipt_source where sourceId = '$array[id]')) and classify in ('核销', '付款单核销', '付款单')",
                    'sum' => "money"
                ]);
                //调整金额
                $adjustMoney = find([
                    'table' => 'purchase_esti_order_detail as a join purchase_get_order_detail as b on a.sourceId = b.id join purchase_order as main on b.orderId = main.id join inventory_detail as c on c.sourceId = a.id join record as d on c.id = d.sourceId',
                    'single' => "a.coid = '" . self::$coid . "' and main.orderNo = '$array[orderNo]'",
                    'field' => "ifnull(sum(d.money),0) as money"
                ])['money'];
                $adjustMoney = -$adjustMoney;
                $saleMoney = $saleMoney != 0 ? -$saleMoney : 0;
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '单据编号'=>$array['orderNo'],
                            '单据日期'=>$array['recordDate'],
                            '结算方式'=>$settlementType,
                            '结算期限'=>$period,
                            '供应商编码'=>$array['code'],
                            '供应商'=>$array['name'],
                            '供应商类别'=>$array['category'],
                            '应付金额'=>self::lostZero($saleMoney + $adjustMoney),
                            '实际付款金额'=>self::lostZero($recMoney),
                            '剩余应付金额'=>self::lostZero(round($saleMoney + $adjustMoney - $recMoney, 2)),
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了" . self::title;
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, self::title . ".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }
    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'单据编号',
                    'aliasName'=>'单据编号',
                ],
                [
                    'columnName'=>'单据日期',
                    'aliasName'=>'单据日期',
                ],
                [
                    'columnName'=>'结算方式',
                    'aliasName'=>'结算方式',
                ],
                [
                    'columnName'=>'结算期限',
                    'aliasName'=>'结算期限',
                ],
                [
                    'columnName'=>'供应商编码',
                    'aliasName'=>'供应商编码',
                ],
                [
                    'columnName'=>'供应商',
                    'aliasName'=>'供应商',
                ],
                [
                    'columnName'=>'供应商类别',
                    'aliasName'=>'供应商类别',
                ],
                [
                    'columnName'=>'应付金额',
                    'aliasName'=>'应付金额(元)',
                ],
                [
                    'columnName'=>'实际付款金额',
                    'aliasName'=>'实际付款金额(元)',
                ],
                [
                    'columnName'=>'剩余应付金额',
                    'aliasName'=>'剩余应付金额(元)',
                ],
            ]
        };
    }
}

